const { createOrder, findAllOrder, updateOrder } = require("../service/order.service");
const {
  createOrderFail,
  createOrderError,
  findAllOrderFail,
  findAllOrderError,
  updateOrderFail,
  updateOrderError,
} = require("../constant/error.type");

class OrderController {
  async create(ctx) {
    try {
      const user_id = ctx.state.user.id;
      const { address_id, goods_info, total } = ctx.request.body;
      const res = await createOrder({ user_id, address_id, goods_info, total });
      if (res) {
        ctx.body = {
          code: 0,
          message: "创建订单成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", createOrderFail, ctx);
      }
    } catch (error) {
      console.error("创建订单出错", error);
      return ctx.app.emit("error", createOrderError, ctx);
    }
  }
  async findAll(ctx) {
    try {
      const { pageNum = 1, pageSize = 10, status = 0 } = ctx.request.query;
      const res = await findAllOrder(pageNum, pageSize, status);
      if (res) {
        ctx.body = {
          code: 0,
          message: "获取订单列表成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", findAllOrderFail, ctx);
      }
    } catch (error) {
      console.error("获取订单列表出错", error);
      return ctx.app.emit("error", findAllOrderError, ctx);
    }
  }
  async update(ctx) {
    try {
      const id = ctx.request.params.id;
      const { status } = ctx.request.body;
      const res = await updateOrder(id, status);
      if (res) {
        ctx.body = {
          code: 0,
          message: "更新订单状态成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", updateOrderFail, ctx);
      }
    } catch (error) {
      console.error("更新订单状态出错", error);
      return ctx.app.emit("error", updateOrderError, ctx);
    }
  }
}

module.exports = new OrderController();
